package com.medata.utils;

import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

//加盐+md5加密
public class Md5SaltUtil {
    private static char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public String salt() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(16);
        for (int i = 0; i < sb.capacity(); i++) {
            sb.append(hex[random.nextInt(16)]);
        }
        return sb.toString();
    }

    //随机盐,并生成HashSalt,并返回Map<salt,HashSalt>
    public Map<String, String> getHashSalt(String password) {
        String salt = salt();
        System.out.println(salt);
        String PSalt = password + salt;
        System.out.println(PSalt);
        String HashSalt = DigestUtils.md5DigestAsHex(PSalt.getBytes());
        System.out.println(HashSalt);
        Map<String, String> map = new HashMap<String, String>();
        map.put(salt, HashSalt);
        return map;
    }

    //以用户名为盐,进行加盐加密
    public String getHashNameSalt(String password, String name) {
        String PSalt = name + password;
        String HashSalt = DigestUtils.md5DigestAsHex(PSalt.getBytes());
        return HashSalt;
    }


    //验证密码是否正确
    public Boolean VerifyPassword(String salt, String password, String HashSalt) {
        String PSalt = password + salt;
        System.out.println(PSalt);
        String HS = DigestUtils.md5DigestAsHex(PSalt.getBytes());
        return HS.equals(HashSalt) ? true : false;
    }


    //测试
    public static void main(String[] args) {
        Md5SaltUtil saltUtils = new Md5SaltUtil();
//		Map<String, String> hashSalt = saltUtils.getHashSalt("aaa");
//		System.out.println(hashSalt);
//		Boolean flag = saltUtils.VerifyPassword("851FA0B49AD0B60B", "aaa", "615f268e8747d89b697ba9007fc92f8a");
//		System.out.println(flag);
		 String hashNameSalt = saltUtils.getHashNameSalt("editor", "editor");
		 System.out.println(hashNameSalt);
    }
}
